//
//  MQRefreshControl.swift
//  SinaWeiBo
//
//  Created by 毛强 on 16/1/24.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
private let refreshControlH:CGFloat = 50
/**
 下拉刷新状态
 
 - Normal:  正常状态
 - Pulling: 放飞即可刷新状态
 - Refresh: 刷新状态
 */
enum RefreshControlState:Int{
    case Normal = 0
    case Pulling = 1
    case Refreshing = 2
}

class MQRefreshControl: UIControl {
    
    private var refreshState:RefreshControlState = .Normal{
        didSet{
            switch refreshState{
            case .Pulling :
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                messageLabel.text = "放开起飞"
                
            case .Normal : UIView.animateWithDuration(1, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                messageLabel.text = "下拉刷新"
                arrowIcon.hidden = false
                activityView.stopAnimating()
                
            case .Refreshing :
                activityView.startAnimating()
                arrowIcon.hidden = true
                messageLabel.text = "正在加载"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var contentInset = self.scrollview!.contentInset
                    contentInset.top = contentInset.top + refreshControlH
                    self.scrollview?.contentInset = contentInset
                })
                
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
            }
        }
    }
    
    private var scrollview:UIScrollView?
    override init(frame: CGRect) {
        super.init(frame:frame)
        self.backgroundColor = UIColor.blueColor()
        self.frame.size = CGSizeMake(SCREENW, refreshControlH)
        self.frame.origin.x = 0
        self.frame.origin.y = -self.frame.height
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func endRefreshing(){

        if refreshState == .Refreshing {
            refreshState = .Normal
            UIView.animateWithDuration(0.25) { () -> Void in
                var contentInset = self.scrollview!.contentInset
                contentInset.top = contentInset.top - refreshControlH
                self.scrollview!.contentInset = contentInset
            }
        }
       
    }
    
    private func setupUI(){
        //添加控件
        addSubview(arrowIcon)
        addSubview(messageLabel)
        addSubview(activityView)
        
        //添加约束
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.leading.equalTo(arrowIcon.snp_trailing)
        }
        
        activityView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(arrowIcon)
            make.centerY.equalTo(arrowIcon)
        }
        
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        let scrollview = newSuperview as! UIScrollView
        self.scrollview = scrollview
        self.frame.size.width = scrollview.frame.size.width
        
        scrollview.addObserver(self, forKeyPath: "contentOffset", options: [NSKeyValueObservingOptions.New], context: nil)
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        printfLog(keyPath)
//        printfLog(self.scrollview?.contentOffset.y)
        
        let conditionValue:CGFloat = -scrollview!.contentInset.top - refreshControlH
        if scrollview!.dragging {
            if self.scrollview?.contentOffset.y < conditionValue && refreshState == .Normal{
                //下拉刷新状态
                self.refreshState = .Pulling
            }else if self.scrollview?.contentOffset.y >= conditionValue && refreshState == .Pulling{
                //松手起飞状态
                self.refreshState = .Normal
            }
        }else{
            //正在刷新
            if refreshState == .Pulling{
                self.refreshState = .Refreshing
            }
        }
    }
    
    deinit{
        self.scrollview?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    // MARK: - 懒加载控件
    private lazy var arrowIcon:UIImageView = {
        let arrowIcon = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
        return arrowIcon
    }()
    private lazy var messageLabel:UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 15)
        label.text = "下拉刷新"
        return label
    }()
    private lazy var activityView:UIActivityIndicatorView = {
        let activityView = UIActivityIndicatorView()
//        activityView.startAnimating()
        return activityView
    }()
}
